package us.mooresr.aircraftscheduling.server.handler;

import us.mooresr.aircraftscheduling.server.BCrypt;
import us.mooresr.aircraftscheduling.server.DAO;
import us.mooresr.aircraftscheduling.shared.action.CreateUserAction;
import us.mooresr.aircraftscheduling.shared.action.CreateUserResult;
import us.mooresr.aircraftscheduling.shared.action.UpdateUserAction;
import us.mooresr.aircraftscheduling.shared.action.UpdateUserResult;
import us.mooresr.aircraftscheduling.shared.model.User;
import us.mooresr.aircraftscheduling.shared.model.UserDetail;

import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.gwtplatform.dispatch.shared.ActionException;

public class UpdateUserHandler implements ActionHandler<UpdateUserAction, UpdateUserResult> {

	@Override
	public UpdateUserResult execute(UpdateUserAction action, ExecutionContext context)
			throws ActionException {
		//
		// The only thing different between Update and Create is that in Update we
		// want to preserve the old password if a new one hasn't been provided
		//
		
		DAO dao = new DAO();
		
		User newUser = action.getUser();
		UserDetail newUserDetail = action.getUserDetail();
		
		if (newUserDetail.getHashedPassword().length() == 0) {
			// No new password provided, grab the old one
			UserDetail oldUserDetail = dao.ofy().get(UserDetail.class, newUserDetail.getId());
			newUserDetail.setHashedPassword(oldUserDetail.getHashedPassword());
		} else {
			// New password provided.  The password is in cleartext.  We need to hash it.
			String plainPassword = newUserDetail.getHashedPassword();
			
			String newHashedPassword = BCrypt.hashpw(plainPassword, BCrypt.gensalt());
			
			newUserDetail.setHashedPassword(newHashedPassword);
		}
		

		dao.ofy().put(newUser);
		
		newUserDetail.setId(newUser.getUserId());
		
		
		dao.ofy().put(newUserDetail);
		
		return new UpdateUserResult(newUser);
		
	}

	@Override
	public Class<UpdateUserAction> getActionType() {
		return UpdateUserAction.class;
	}

	@Override
	public void undo(UpdateUserAction arg0, UpdateUserResult arg1,
			ExecutionContext arg2) throws ActionException {
		
		
	}

}
